#include <string>
#include <iostream>
#include <string>
#include <cerrno>
#include <cstring>
#include <stdio.h>
#include <unistd.h>
#include <signal.h>
#include "comm.hpp"

#define Retry_Count 5

bool visitServer(std::string &serverip, uint16_t serverport, int *cnt)
{
    // 填充服务端信息
    char server_list[1024];

    std::string inbuffer;
    ssize_t n=0,m=0;
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
    {
        std::cerr << "socket error" << std::endl;
        return false;
    }
    bool ret=true;
    // 先关闭描述符，再返回结果

    struct sockaddr_in server;
    bzero(&server,sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);

    inet_pton(AF_INET, serverip.c_str(), &server.sin_addr);

    // 不需要显示绑定自身信息

    // 自动绑定
    n = connect(sockfd, CONV(&server), sizeof(server));
    if (n < 0)
    {
        std::cerr << "connect error" << std::endl;
        ret = false;
        goto END;
    }

    // 连接成功后设为还有5次机会
    *cnt = 1;

    // 通信
    m = read(sockfd, server_list, sizeof(server_list) - 1);
    if(m>0)
    {
        server_list[m]=0;
        std::cout <<"服务列表:"<<server_list<<std::endl;
    }
    std::cout << "选择服务: ";
    getline(std::cin, inbuffer);
    write(sockfd, inbuffer.c_str(), inbuffer.size());


    // 往fd中写入
    std::cout <<  "Enter> ";
    getline(std::cin, inbuffer);
    if(inbuffer=="quite")
        return true;
    n=write(sockfd, inbuffer.c_str(), inbuffer.size());
    if (n > 0)
    {
        char buffer[1024];
        m = read(sockfd, buffer, sizeof(buffer) - 1);
        if (m > 0)
        {
            buffer[m] = 0;
            std::cout  << buffer << std::endl;
        }
        // 读到结尾
        else if (m == 0)
        {
            return true;
        }
        else
        {
            ret = false;
            goto END;
        }
    }
    else
    {
        ret = false;
        goto END;
    }

END:
    close(sockfd);
    return ret;
}

void Usage(const std::string proc)
{
    std::cout << "Usage :\n\t" << proc << "server.ip server.port" << std::endl;
}

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(Usage_err);
    }

    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);

    // 防止服务器杀死客户端
    signal(SIGPIPE, SIG_IGN);

    int cnt = 1;
    while (cnt <= Retry_Count)
    {
        bool result = visitServer(serverip, serverport, &cnt);
        if (result)
        {
            break;
        }
        else
        {
            sleep(1);
            std::cout << "server offline,retying....count:" << cnt << std::endl;
            cnt++;
        }
    }
    if (cnt == Retry_Count)
    {
        std::cout << "server offline...." << std::endl;
    }

    return 0;
}